package com.minelx.sqlstructures.statements.parse.select.where;

import com.minelx.sequence.core.Match;
import com.minelx.sequence.core.ReturnMatcher;
import com.minelx.sequence.core.StringScanner;
import com.minelx.sqlstructures.common.parse.JoinMatcher;
import com.minelx.sqlstructures.statements.clause.AndBuilder;
import com.minelx.sqlstructures.statements.clause.Sql;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class AndBuilderParser implements ReturnMatcher<AndBuilder, StringScanner> {
	private static final String WHERE = "WHERE";

	private final ReturnMatcher<Sql, StringScanner> conditionsMatcher;

	private AndBuilderParser() {
		conditionsMatcher = new JoinMatcher<>(
				Match.content(" AND "),
				new EqMatcher().or(new InMatcher())
		);
	}

	@Override
	public boolean isMatch(StringScanner source) {
		source.trim();
		return source.exists(WHERE);
	}

	@Override
	public AndBuilder onMatched(StringScanner source) {
		source.goes(WHERE);
		source.trim();
		List<Sql> conditions = source.stream(conditionsMatcher).collect(toList());
		return AndBuilder.create(conditions.stream().map(Sql::toText).collect(toList()));
	}

	public static ReturnMatcher<AndBuilder, StringScanner> create() {
		return new AndBuilderParser();
	}
}
